import axios from 'axios'
import storage from '@/utils/storage'
import router from '@/router'
import { delCookie } from "@/config/cookie";
import { MessageBox } from 'element-ui'

const service = axios.create({
    baseURL: process.env.NODE_ENV == 'production' ? '/' : '/',
    timeout: 5000000 // request timeout
})


service.interceptors.request.use(
    config => {
        if (storage.get('token')) {
            config.headers['Authorization'] = 'Bearer ' + storage.get('token') // 让每个请求携带自定义token 请根据实际情况自行修改
        }

        return config
    },
    error => {
        Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        const res = response.data
        if (res && res.code == 200) {
            return Promise.resolve(res)
        } else if (res && res.code == 500) {

            MessageBox.alert('没有权限，是否重新登录？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                storage.remove("user");
                storage.remove("tree");
                delCookie("isLogin");
                router.replace({ path: "/login" })
            })
            return Promise.reject(res.msg || "没有权限")
        } else {
            MessageBox.alert('请求错误，重新登录', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                storage.remove("user");
                storage.remove("tree");
                delCookie("isLogin");
                router.replace({ path: "/login" })
            })
            return Promise.reject(res.msg || "请求异常")
        }
    },
    error => {
        MessageBox.alert('请求错误，重新登录', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
        }).then(() => {
            storage.remove("user");
            storage.remove("tree");
            delCookie("isLogin");
            router.replace({ path: "/login" })
        })
    }
)

export default service;
